package dao;

import entity.User;

import java.sql.*;



public class UserDao {
    //增
    public int add(User user, Connection connection) throws SQLException {
        String sql = "insert into user_info(user_name,user_sex,address_id) values (?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, user.getUserName());
        statement.setString(2, user.getUserSex());
        statement.setInt(3,user.getAddressId());
        int count = statement.executeUpdate();
        statement.close();
        return count;
    }




    //删
    public int delete(int userId, Connection connection) throws SQLException {
        String sql = "delete from user_info where user_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,userId);

        int count = statement.executeUpdate();


        statement.close();
        return count;

    }





    //改
        public int update(User user, Connection connection) throws SQLException {
            String sql = "update user_info set user_name = ?,user_sex = ?,address_id = ? where user_id = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, user.getUserName());
            statement.setString(2, user.getUserSex());
            statement.setInt(3,user.getAddressId());
            statement.setInt(4, user.getUserId());
            int count = statement.executeUpdate();
            statement.close();
            return count;
        }
    //查
    public User selectById(int userId, Connection connection) throws SQLException {
        String sql = "select * from user_info where user_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, userId);
        ResultSet resultSet = statement.executeQuery();
        User user = null;
        while (resultSet.next()){
            String userName = resultSet.getString("user_name");
            String userSex = resultSet.getString("user_sex");
            int addressId = resultSet.getInt("address_id");
            user = new User(userId,userName,userSex,addressId);
            break;
        }



        resultSet.close();
        statement.close();
        return user;
    }
}
